from client.redis_client import r
from dao.es_dao.card_dao import update_card_wearing, \
    update_health, get_card
from dao.es_dao.p_health_log_dao import save_all_health
from dao.mongo_dao.wechat_login_dao import find_wechat_login
from model.es.card import ElectronicCardModel
from model.wristband_models import HealthData, WarningData
from service.battery import get_intensity_redis
from utils.date_utils import timestamp_to_str
from utils.health_utils import blood_pressure_valid, generate_heart_rate_wechat_template, temperature_valid, \
    build_body_temperature_keyword
from utils.wechat_message_util import WechatTokenManager, build_wechat_message_data, send_template_message, alert_data


async def handle_health(health: HealthData):
    card_doc: ElectronicCardModel = await get_card(health.device_id)
    _id = card_doc.es_id
    if health.heart_rate is not None and health.heart_rate > 0:
        await update_card_wearing(True, _id)
    r.hset('state_' + health.device_id, 'online', 1)  # 检测到有健康数据则为在线状态
    await update_health(health)
    # 血压验证

    token = None
    openid_list = None
    intensity_dict: dict = await get_intensity_redis(health.device_id)
    intensity = intensity_dict['intensity']
    await save_all_health(health, card_doc.dataAuthority.model_dump(), intensity_dict)

    body_pressure_data = blood_pressure_valid(health.blood_pressure_high, health.blood_pressure_low)
    clock_state = r.hget('clock_state', health.device_id)
    if clock_state is not None and clock_state == b'1' and intensity < 2:
        if body_pressure_data is not None:
            print('记录日志存入预警数据表格')
            if body_pressure_data['warning_level'] > 2:
                if openid_list is None:
                    openid_list = find_wechat_login(str(card_doc.depart))
                token_manager = WechatTokenManager()
                token = await token_manager.get_token()
                body_pressure_keyword_data = {
                    'thing4': {'value': card_doc.name, "color": "#173177"},
                    'character_string3': {'value': body_pressure_data['value']},
                    'const5': {'value': body_pressure_data['blood_pressure_level']},
                    'time1': {'value': timestamp_to_str(float(health.timestamp))},
                    'const10': {'value': body_pressure_data['advice']}
                }
                message_data = build_wechat_message_data(keyword_data=body_pressure_keyword_data,
                                                         openid_list=openid_list,
                                                         template_id='W3m9Rpek7r97XkK3d2ztp24JcgqmdKqdLORplbW3Cj8')
                for message in message_data:
                    await send_template_message(message, token)
        # 心率验证
        heart_rate_data = await generate_heart_rate_wechat_template(health.heart_rate, health.device_id,
                                                                    card_doc.name,
                                                                    health.timestamp, intensity)
        if heart_rate_data is not None:
            if openid_list is None:
                openid_list = find_wechat_login(str(card_doc.depart))
            if token is None:
                token_manager = WechatTokenManager()
                token = await token_manager.get_token()

            heart_message_data = build_wechat_message_data(keyword_data=heart_rate_data,
                                                           openid_list=openid_list,
                                                           template_id='BbC-bhVMxpNM3j790moW-LN_go84mnpKAURAjkQfnwQ')
            for message in heart_message_data:
                await send_template_message(message, token)
        if health.body_temperature > 0:
            temperature_alert = temperature_valid(float(health.body_temperature))
            if temperature_alert is not None:
                if openid_list is None:
                    openid_list = find_wechat_login(str(card_doc.depart))
                if token is None:
                    token_manager = WechatTokenManager()
                    token = await token_manager.get_token()
                temperature_keyword = build_body_temperature_keyword(temperature_alert, health.body_temperature,
                                                                     card_doc.depart_name,
                                                                     card_doc.name, float(health.timestamp))
                temperature_message_data = build_wechat_message_data(keyword_data=temperature_keyword,
                                                                     openid_list=openid_list,
                                                                     template_id='nGFpGtRdS9ARfIsCJ8ZckZfLkDlJFIvOb_p_zcwPtbY')
                for message in temperature_message_data:
                    await send_template_message(message, token)


async def handle_warning(data: WarningData):
    if int(data.type) == 2:
        await alert_data(data, '发起了SOS求救')
    elif int(data.type) == 13:
        card_doc = await get_card(data.device_id)
        await update_card_wearing(False, card_doc.es_id)


